import json
from datetime import datetime
import redis
from flask import current_app
from models import News

class BaseRedisConnection(object):
    def __init__(self):
        # 直连
        # self.conn = redis.Redis(
        #     host='localhost',
        #     port=6379,
        #     db=1,
        #     decode_responses=True
        # )
        # 连接池连接
        # pool = redis.ConnectionPool(
        #     host='localhost',
        #     port=6379,
        #     db=1,
        #     max_connections=20,
        #     decode_responses=True
        # )
        # self.conn = redis.Redis(
        #     connection_pool=pool
        # )

        # 从配置文件读取redis相关的配置
        redis_config = current_app.config['REDIS_SETTINGS']
        pool = redis.ConnectionPool(
            **redis_config
        )
        self.conn = redis.Redis(
            connection_pool=pool
        )



    def __del__(self):
        try:
            print('关闭连接池')
            self.conn.close()
        except Exception as e:
            print(e)



class NewsCache(BaseRedisConnection):

    def set_index_news(self):
        # 缓存首页热点新闻信息
        queryset = News.query.filter(News.is_valid == True,News.is_top == True).order_by(News.created_at.desc()).all()
        news_list = []
        for item in queryset:
            print(item.to_dict())
            news_list.append(item.to_dict())
        key = current_app.config['INDEX_NEWS_KEY']
        data = {
            key:news_list,
            't':datetime.now().timestamp()
        }
        result = self.conn.set(key,json.dumps(data))
        print('缓存完成：',result)


    def get_index_news(self):
        # 获取首页的热点新闻
        key = current_app.config['INDEX_NEWS_KEY']
        result = self.conn.get(key)
        # 没有被缓存
        if result is None:
            self.set_index_news()
            result = self.conn.get(key)
        news_info = json.loads(result)
        return news_info[key]